package com.sergiandreplace.kaboom.browser;

import java.util.Arrays;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sergiandreplace.kaboom.R;
import com.sergiandreplace.kaboom.comic.Comic;

public class FileIconAdapter extends ArrayAdapter<FileIcon>
{
	public static final int THUMBNAIL_SIZE = 256;

	private Context context = null;
	private FileIcon[] fileIcons;

	public FileIcon[] getFileIcons()
	{
		return fileIcons;
	}

	public void setFileIcons(FileIcon[] fileIcons)
	{
		this.fileIcons = fileIcons;
	}

	String path = null;

	public FileIconAdapter(Context context, FileIcon[] icons, String path)
	{
		super(context, R.id.fileName, icons);
		Arrays.sort(icons);
		this.context = context;
		this.fileIcons = icons;
		this.path = path;
		if (!this.path.matches(".*/")) this.path = this.path + "/";

	}

	@Override
	public View getView(int position, View v, ViewGroup parent)
	{
		if (fileIcons[position].getIconView() == null)
		{
			LayoutInflater li = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = li.inflate(R.layout.file_icon, null);
			fileIcons[position].setIconView(v);
		}
		else
		{
			v = fileIcons[position].getIconView();
		}
		((TextView) v.findViewById(R.id.fileName)).setText(fileIcons[position].getName());
		TextView typeTextView = (TextView) v.findViewById(R.id.fileType);
		ImageView fileIcon = ((ImageView) v.findViewById(R.id.fileIcon));
		ImageView comicIcon = ((ImageView) v.findViewById(R.id.comicIcon));
		FileType type = fileIcons[position].getType();
		typeTextView.setText(type.getDescription());
		fileIcon.setImageResource(type.getIcon(path, fileIcons[position].getName()));
		if (!type.isComic())
		{
			fileIcon.setVisibility(View.VISIBLE);
			comicIcon.setVisibility(View.INVISIBLE);

		}
		else
		{
			if (fileIcons[position].getThumbnail() != null)
			{
				comicIcon.setImageBitmap(fileIcons[position].getThumbnail());
				fileIcon.setVisibility(View.INVISIBLE);
				comicIcon.setVisibility(View.VISIBLE);
			}
			else
			{
				comicIcon.setVisibility(View.INVISIBLE);
				((ProgressBar) v.findViewById(R.id.fileProgress)).setVisibility(View.VISIBLE);
				loadThumbnail(fileIcons[position], path);
			}

		}
		return v;
	}

	private void loadThumbnail(FileIcon icon, String path)
	{
		icon.setComic(new Comic(path + icon.getName()));
		icon.getComic().loadComicInfo();
		icon.getComic().loadPage(0, THUMBNAIL_SIZE);

	}

}
